package com.hmdp.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_TTL;

@Component
@Slf4j
/**
 * Redis工具类
 */
public class RedisClient {
    public final StringRedisTemplate stringRedisTemplate;

    public RedisClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key , Object value, Long time, TimeUnit unit){
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queryWithPassThrough(String key, ID id , Class<R> type, Function<ID,R> dbQueryById,Long time , TimeUnit unit){
        //查询redis缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheShop)){
            //如果redis缓存中存在，直接返回商铺数据
            return JSONUtil.toBean(cacheShop, type);
        }
        if (cacheShop != null){
            //如果为空串，返回null
            return null;
        }
        //查询数据库，得到商铺信息
        R r = dbQueryById.apply(id);
        //判断数据库中是否存在该商铺
        if (r != null){
            //如果存在，直接返回并存入redis缓存
            this.set(key,r,CACHE_NULL_TTL,TimeUnit.MINUTES);
            return r;
        }
        //如果不存在,将空串存入redis缓存中
        this.set(key,"",time,unit);
        return null;
    }

    public static final ExecutorService CACHE_EXECUTORS = Executors.newFixedThreadPool(10);

    public <R,ID> R queryWithLogicalExpire(String key, String keyLock ,ID id , Class<R> type,
                                           Function<ID,R> dbQueryById,Long time , TimeUnit unit){
        //查询redis缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(cacheShop)){
            //如果不存在，直接返回空
            return null;
        }
        //如果存在,先得到data数据,判断是否过期
        RedisData redisData = JSONUtil.toBean(cacheShop, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        LocalDateTime expireTime = redisData.getExpireTime();
        R r = JSONUtil.toBean(data, type);
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期,直接返回r
            return r;
        }
        //已过期，尝试获取互斥锁
        Boolean isLock = tryLock(keyLock);
        if (isLock){
            //获取锁成功,再次判断redis缓存数据是否过期
            String cacheShopDouble = stringRedisTemplate.opsForValue().get(key);
            RedisData redisDataDouble = JSONUtil.toBean(cacheShopDouble, RedisData.class);
            LocalDateTime expireTimeDouble = redisDataDouble.getExpireTime();
            if (expireTimeDouble.isAfter(LocalDateTime.now())){
                //未过期,直接返回商铺信息
                JSONObject shopDataDouble = null;
                try {
                    shopDataDouble = (JSONObject) redisDataDouble.getData();
                    return JSONUtil.toBean(shopDataDouble, type);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(keyLock);
                }
            }
            //已过期，创建新线程，查询数据库对实现redis缓存重建
            CACHE_EXECUTORS.submit(() ->{
                try {
                    R r1 = dbQueryById.apply(id);
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(keyLock);
                }
            });
        }
        //获取锁失败，直接返回过期信息
        return r;
    }

    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return flag != null && flag;
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
